<template>
  <div class="video-wrap" :style="{ width, height }">
    <div ref="oVideoWrap" id="mse"></div>
    <div v-if="isShowCover" class="video-cover">视频正在加载中...</div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue';

import Player from 'xgplayer';
import 'xgplayer/dist/index.min.css'

const props = defineProps({
  width: { type: String, default: '100%' },
  height: { type: String, default: '100%' },
  source: { type: String, default: '' },
  message: { type: Object, default: () => ({}) },
})
const isShowCover = ref(true);
const emit = defineEmits(['play', 'end']);

let player = null;
let isPlay = false;

const curSource = ref(props.source);

//  接收需要播放的视频资源
watch(() => props.source, (val) => {
  curSource.value = val;
  player = createPlayer();
})

onMounted(() => {
  props.source && (player = createPlayer());
})

//  销毁 player
function destroyPlayer() {
  if(player) {
    player.destroy();
  }

  player = null;
}

const createPlayer = () => {
  //  存在就先销毁
  destroyPlayer();
  const player = new Player({
    el: oVideoWrap.value,
    url: curSource.value,
    width: '100%',
    height: '100%',
    autoplay: false,
    volume: 0.3,
    lang: 'zh-cn',
    poster: props.message.image,
    playsinline: false,
    'x5-video-player-type': 'h5', //  同层播放
    // rotateFullscreen: true, //  支持全屏
    rotate: {   //视频旋转按钮配置项
        innerRotate: true, //只旋转内部video
        clockwise: false // 旋转方向是否为顺时针
    },
    playbackRate: [0.5, 0.75, 1, 1.5, 2], //传入倍速可选数组
    defaultPlaybackRate: 1, //  默认倍速
    videoInit: true
  });

  //  监听 初始化完成事件
  player.once('ready',() => {
    isShowCover.value = false;
  })

  //  监听视频播放结束
  player.on('ended', () => {
    emit('ended');
  })

  //  缓存函数
  const play = player.play.bind(player);

  //  对其内部方法进行二次封装
  player.play = function() {
    !isPlay && emit('play');
    play(); //  对其进行二次封装
    isPlay = true;
  }
  //  创建一个新的 player, 对其原先的方法进行二次封装
  const playerObj = Object.create(player, {
    play() {
      player.play();
    }
  })

  return player;
}

//  视频播放器容器
const oVideoWrap = ref(null);
</script>

<style lang="scss" scoped>

.video-wrap {
  position: relative;

  .video-cover {
    position: absolute;
    top: 0;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    font-size: 1.6rem;
    color: #fff;
    background: black;
  }
}

#mse {
  box-sizing: border-box;
}
</style>
